package com.aps.apspda.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.AlarmListAdapter;
import com.aps.apspda.adapter.ChildEqpListAdapter;
import com.aps.apspda.adapter.InputDataListAdapter;
import com.aps.apspda.adapter.PopDownAreaListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DbChildCallback;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.StringCommonCallBack;
import com.aps.apspda.dialog.ChooseDieSeqFragmentDialog;
import com.aps.apspda.dialog.DeleteFragmentDialog;
import com.aps.apspda.dialog.GeneralPop;
import com.aps.apspda.dialog.LoadingDialog;
import com.aps.apspda.dialog.WarnFragmentDialog;
import com.aps.apspda.entity.AlarmEntity;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.ChildEqpEntity;
import com.aps.apspda.entity.DieSeqGridEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.InputDataEntity;
import com.aps.apspda.entity.InputDatasEntity;
import com.aps.apspda.entity.LotEndEntity;
import com.aps.apspda.entity.NewEqpEntity;
import com.aps.apspda.entity.PicEntity;
import com.aps.apspda.myview.ClearEditText;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.NumberUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.StringUtils;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.aps.apspda.activity.StartFunctionActivity.showPicPop;

public class EndFunctionActivity extends BaseActivity {


    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.tvLogId)
    TextView tvLogId;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.etTouNum)
    ClearEditText etTouNum;
    @BindView(R.id.tvPlanNum)
    TextView tvPlanNum;
    @BindView(R.id.etTrueNum)
    EditText etTrueNum;
    @BindView(R.id.tvPassRate)
    TextView tvPassRate;//add by bunny
    @BindView(R.id.tvOpen)
    TextView tvOpen;//add by bunny
    @BindView(R.id.tvUph)
    TextView tvUph;
    @BindView(R.id.rvAlarmList)
    RecyclerView rvAlarmList;
    @BindView(R.id.etRemark)
    EditText etRemark;
    @BindView(R.id.tvSubmitRemark)
    TextView tvSubmitRemark;
    @BindView(R.id.rvInputList)
    RecyclerView rvInputList;
    @BindView(R.id.ivDownArrow2)
    ImageView ivDownArrow2;
    @BindView(R.id.tvChoose)
    TextView tvChoose;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etBladeExp)
    ClearEditText etBladeExp;
    @BindView(R.id.llBladeExp_end)
    LinearLayout llBladeExp_end;
    @BindView(R.id.tvPlanNum_end)
    LinearLayout tvPlanNum_end;
    @BindView(R.id.etTouNum_end)
    LinearLayout etTouNum_end;
    @BindView(R.id.Uph_modeType_end)
    LinearLayout Uph_modeType_end;
    @BindView(R.id.UphmodeType)
    ClearEditText UphmodeType;
    @BindView(R.id.UphId)
    LinearLayout UphId;
    @BindView(R.id.rlInput)
    RelativeLayout rlInput;
    private LotEndEntity lotEndEntity;
    private AlarmListAdapter alarmListAdapter;
    private Animation animation, animationDismiss;
    private InputDataListAdapter inputDataListAdapter;
    private List<InputDatasEntity.InputObjects> inputList = new ArrayList<>();
    private InputDatasEntity.InputObjects currentInputObject = new InputDatasEntity.InputObjects();
    private List<InputDataEntity.InputObject> submitInputList = new ArrayList<>();
    private LoadingDialog dialog;
    private GeneralPop generalPop;
    private String  eqpType;   //全局变量，通过eqptype来判断是否需要展示刀片暴露量
    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            EndFunctionActivity.this.finish();
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_end_function;
    }

    @Override
    protected void initView() {
        rvInputList.setLayoutManager(new LinearLayoutManager(EndFunctionActivity.this));
        rvInputList.setItemAnimator(new DefaultItemAnimator());
        rvInputList.addItemDecoration(new DividerItemDecoration(EndFunctionActivity.this, 1));

        rvAlarmList.setLayoutManager(new LinearLayoutManager(EndFunctionActivity.this));
        rvAlarmList.setItemAnimator(new DefaultItemAnimator());
        rvAlarmList.addItemDecoration(new DividerItemDecoration(EndFunctionActivity.this, 1));
        llBladeExp_end.setVisibility(View.GONE);
        Uph_modeType_end.setVisibility(View.GONE);
     /*   if (StaticMembers.isOffLine) {
            if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
                llBladeExp_end.setVisibility(View.VISIBLE);
            }else{
                llBladeExp_end.setVisibility(View.GONE);
            }
        } else {
            llBladeExp_end.setVisibility(View.GONE);
        }*/
        topView.setTitle("批次结束(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        topView.setTitleMode(TitleView.NORMAL_TEXT_MODE);
        topView.setRightListener("结束作业", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (StaticMembers.isOffLine) {
                    if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
                        llBladeExp_end.setVisibility(View.VISIBLE);
                        etBladeExp.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    }else{
                        llBladeExp_end.setVisibility(View.GONE);
                    }
                } else {
                    llBladeExp_end.setVisibility(View.GONE);
                }
                final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                deleteFragmentDialog.setData("确定要结束作业吗？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteFragmentDialog.dismiss();
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        if (etTrueNum.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请填写实际产量后再结束作业",
                                    EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        //add by bunny
                        if (etTouNum.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请填写投料数量后再结束作业",
                                    EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        if (tvPassRate.getText().toString().trim().length() > 0 && Float.parseFloat(tvPassRate.getText().toString()) > 100) {
                            final DeleteFragmentDialog deleteFragmentDialog2 = new DeleteFragmentDialog();
                            deleteFragmentDialog2.setData("合格率大于100，请确认实际产量，是否继续结束作业？", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteFragmentDialog2.dismiss();
                                    checkAndsubmitData();
                                }
                            });
                            deleteFragmentDialog2.show(getSupportFragmentManager(), "delete_dialog");
                        } else {
                            checkAndsubmitData();
                        } //add by bunny
                    }
                });
                deleteFragmentDialog.show(getSupportFragmentManager(), "delete_dialog");
            }

        });
        //add by bunny
        etTouNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() != 0 && NumberUtils.isNumber(editable.toString()) && etTrueNum.getText().length() != 0 && NumberUtils.isNumber(etTrueNum.getText().toString())) {
                    float f_tounum = Float.parseFloat(editable.toString());
                    float f_truevalue = Float.parseFloat(etTrueNum.getText().toString());
                    DecimalFormat df = new DecimalFormat("0.00");
                    String data = df.format((float) f_truevalue / f_tounum * 100);
                    tvPassRate.setText(data);
                }
            }
        });
        etTrueNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() != 0 && NumberUtils.isNumber(editable.toString()) && etTouNum.getText().length() != 0 && NumberUtils.isNumber(etTouNum.getText().toString())) {
                    float f_tounum = Float.parseFloat(etTouNum.getText().toString());
                    float f_truevalue = Float.parseFloat(editable.toString());
                    DecimalFormat df = new DecimalFormat("0.00");
                    String data = df.format((float) f_truevalue / f_tounum * 100);
                    tvPassRate.setText(data);
                }
            }
        });
    }

    private void checkAndsubmitData() {
        if (lotEndEntity != null) {
            boolean isOk = true;
            if (inputDataListAdapter != null) {
                submitInputList = inputDataListAdapter.getData();
                for (InputDataEntity.InputObject inputObject : submitInputList) {
                    if (inputObject.getISNULL().equalsIgnoreCase("Y") &&
                            inputObject.getDATAVALUE().length() == 0) {
                        ToastUtils.showFreeToast("请填写带*栏数据", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                        isOk = false;
                    } else {
                        if (inputObject.getDATAVALUE().toUpperCase().contains("NG")) {
                            String[] strs = inputObject.getDATAVALUE().split(";");
                            if (strs.length <= 1) {
                                isOk = false;
                                ToastUtils.showFreeToast("请给NG项填写原因", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            }
                        }
                    }
                    if (!isOk) {
                        break;
                    }
                }
            }
            if (isOk) {
                if (getEqpID().toLowerCase().contains("fb") ||
                        getEqpID().toLowerCase().contains("fd"))   {
                    requestEndWorkWithoutDialog();
                    if (dialog == null) {
                        dialog = new LoadingDialog();
                        dialog.setRequestTag("end_loading_dialog");
                    }
                    dialog.show(getSupportFragmentManager(), "end_loading_dialog");
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismissAllowingStateLoss();
                            ToastUtils.showFreeToast("后台正在处理，请等待30秒再操作PDA",
                                    EndFunctionActivity.this, true, 3);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    EndFunctionActivity.this.finish();
                                }
                            }, 3000);
                        }
                    }, 5000);
                } else {
                    requestEndWork();
                }
            }
        }
    }

    private void requestEndWorkWithoutDialog() {
        //ASM和SMD的没有刀片暴露量，注释掉。2019-11-26
        String bladeStr = etBladeExp.getText().toString().trim();
        if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
            if (llBladeExp_end.getVisibility() == View.VISIBLE && StringUtils.isEmpty(bladeStr)) {
                ToastUtils.showFreeToast("请填写刀片暴露量", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                return;
            }
        }
        String uphmodeType = UphmodeType.getText().toString().trim();
        if(eqpType!=null &&(eqpType.equals("FE-DFN-KNSWB"))){
            if (Uph_modeType_end.getVisibility() == View.VISIBLE && StringUtils.isEmpty(uphmodeType)) {
                ToastUtils.showFreeToast("请填写UPH值", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                return;
            }
        }
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new EntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType()) {
            @Override
            public void onSuccess(Response<BaseEntity<FinishLotEntity>> response) {

            }

            @Override
            public void onError(Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EndProcess");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EqpId", getEqpID());
        map.put("LotId", lotEndEntity.getLotId());
        map.put("DoneQty", etTrueNum.getText().toString().trim().length() == 0 ? "0" : etTrueNum.getText().toString().trim());
        map.put("TotalQty", etTouNum.getText().toString().trim().length() == 0 ? "0" : etTouNum.getText().toString().trim());
        map.put("Remark", etRemark.getText().toString().trim());

        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("DATACNNAME", currentInputObject.getDATACNNAME());
            jsonObject2.put("DATANAME", currentInputObject.getDATANAME());
            if (submitInputList.size() == 0) {
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(submitInputList));
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", jsonArray));
            }
            jsonObject.put("INPUTDATA", jsonObject2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        //ASM和SMD的没有刀片暴露量，注释掉。2019-11-26
        if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
            map.put("BladeExp", bladeStr);
        }
        if(eqpType!=null &&(eqpType.equals("FE-DFN-KNSWB"))){
            map.put("UphModeType", uphmodeType);
        }
        NetUtils.requestNet(this, "/EndProcess", map, callBack);
    }

    private void requestEndWork() {
        //ASM和SMD的没有刀片暴露量，注释掉。2019-11-26
        String bladeStr = etBladeExp.getText().toString().trim();
        if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
            if (llBladeExp_end.getVisibility() == View.VISIBLE && StringUtils.isEmpty(bladeStr)) {
                ToastUtils.showFreeToast("请填写刀片暴露量", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                return;
            }
        }
        String uphmodeType = UphmodeType.getText().toString().trim();
        if(eqpType!=null &&(eqpType.equals("FE-DFN-KNSWB"))){
            if (Uph_modeType_end.getVisibility() == View.VISIBLE && StringUtils.isEmpty(uphmodeType)) {
                ToastUtils.showFreeToast("请填写UPH值", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                return;
            }
        }
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EndProcess");
            }

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    // mHandler.postDelayed(runnable, 1000);
                    //  loadSuccess(response.body().getMessage());
                    showdailog(response.body().getMessage());
                    etBladeExp.setText("");
                } else {
                    //loadFail(response.body().getMessage());
                    showdailog(response.body().getMessage());
                }
            }


        };

        Map<String, String> map = new HashMap<>();
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EqpId", getEqpID());
        map.put("LotId", lotEndEntity.getLotId());
        map.put("TotalQty", etTouNum.getText().toString().trim().length() == 0 ? "0" : etTouNum.getText().toString().trim());//add by bunny
        map.put("DoneQty", etTrueNum.getText().toString().trim().length() == 0 ? "0" : etTrueNum.getText().toString().trim());
        map.put("Remark", etRemark.getText().toString().trim());
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("DATACNNAME", currentInputObject.getDATACNNAME());
            jsonObject2.put("DATANAME", currentInputObject.getDATANAME());
            if (submitInputList.size() == 0) {
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(submitInputList));
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", jsonArray));
            }
            jsonObject.put("INPUTDATA", jsonObject2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        //ASM和SMD的没有刀片暴露量，注释掉。2019-11-26
        if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
            map.put("BladeExp", bladeStr);
        }
        if(eqpType!=null &&(eqpType.equals("FE-DFN-KNSWB"))){
            map.put("UphModeType", uphmodeType);
        }
        NetUtils.requestNet(this, "/EndProcess", map, callBack);
    }

    //modify by bunny  弹框点击确认后页面再回主界面
    private void showdailog(String message) {
        final WarnFragmentDialog dialog = new WarnFragmentDialog();
        dialog.setData(message);
        dialog.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mHandler.postDelayed(runnable, 100);
            }
        });
        dialog.show(getSupportFragmentManager(), "check_fail_tips");
    }

    @Override
    protected void initData() {
        eqpType = getIntent().getStringExtra("eqpType");
        if(eqpType==null )
        {
            EntityCallBack<BaseEntity<NewEqpEntity>> callBack = new DialogEntityCallBack<BaseEntity<NewEqpEntity>>
                    (new TypeToken<BaseEntity<NewEqpEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess
                        (final Response<BaseEntity<NewEqpEntity>> response) {
                    if (response.body().isSuccess(EndFunctionActivity.this)) {
                        eqpType = response.body().getData().getEQPINFOLIST().getEQPINFO().get(0).getEQPTYPE();
                        if(eqpType!=null && (eqpType.equals("FE-SMDE-ASMDB")||eqpType.equals("FE-DFN-ASMDB"))){
                            rlInput.setVisibility(View.GONE);
                        }
                        if (StaticMembers.isOffLine) {
                            if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
                                llBladeExp_end.setVisibility(View.VISIBLE);
                                etBladeExp.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                                //UphId.setVisibility(View.GONE);
                            }else{
                                llBladeExp_end.setVisibility(View.GONE);
                            }
                        } else {
                            llBladeExp_end.setVisibility(View.GONE);
                        }
                        if(eqpType!=null && eqpType.equals("Singulation-DISCO")){
                            UphId.setVisibility(View.GONE);
                        }
                        if(eqpType !=null && eqpType.equals("FE-DFN-ASMDB")||eqpType.equals("FE-SMDE-ASMDB")){
                            etTouNum.setEnabled(false);
                            etTouNum.setFocusable(false);
                            etTouNum.setKeyListener(null);//重点
                            //etTouNum.setClearIconVisible(true);
                            //etTouNum.setBackground(null);
                            tvPlanNum_end.setVisibility(View.GONE);
                        }
                    } else {
                        showdailog(response.body().getMessage());
                    }
                }

                @Override
                public void onError
                        (Response<BaseEntity<NewEqpEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "ShowReserveEQPInfoC2E");
                }
            };

            Map<String, String> map = new HashMap<>();
            map.put("EQPID", getEqpID());
            map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
            NetUtils.requestNet(this, "/ShowReserveEQPInfoC2E", map, callBack);
        }else{
            if(eqpType!=null && (eqpType.equals("FE-SMDE-ASMDB")||eqpType.equals("FE-DFN-ASMDB"))){
                rlInput.setVisibility(View.GONE);
            }
            if (StaticMembers.isOffLine) {
                if(eqpType!=null &&(eqpType.equals("DieSaw-DISCO") || eqpType.equals("Singulation-DISCO"))){
                    llBladeExp_end.setVisibility(View.VISIBLE);
                    etBladeExp.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    //UphId.setVisibility(View.GONE);
                }else{
                    llBladeExp_end.setVisibility(View.GONE);
                }
            } else {
                llBladeExp_end.setVisibility(View.GONE);
            }
            if(eqpType!=null && eqpType.equals("Singulation-DISCO")){
                UphId.setVisibility(View.GONE);
            }
            if(eqpType !=null && eqpType.equals("FE-DFN-ASMDB")||eqpType.equals("FE-SMDE-ASMDB")){
                etTouNum.setEnabled(false);
                etTouNum.setFocusable(false);
                etTouNum.setKeyListener(null);//重点
                //etTouNum.setClearIconVisible(true);
                //etTouNum.setBackground(null);
                tvPlanNum_end.setVisibility(View.GONE);
            }
        }
        requestData();
    }

    private void requestData() {
        EntityCallBack<BaseEntity<LotEndEntity>> callBack = new DialogEntityCallBack<BaseEntity<LotEndEntity>>
                (new TypeToken<BaseEntity<LotEndEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LotEndEntity>> response) {
//                if (response.body().getMessage() != null && response.body().getMessage().length() > 0) {
//                    loadFail(response.body().getMessage());
//                }
                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    refreshPop();
                    lotEndEntity = response.body().getData();
                    if (lotEndEntity.getShowAlarm().length() > 0) {
                        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                        View popView = inflater.inflate(R.layout.popupwindow_text, null);
                        final GeneralPop titlePop = new GeneralPop(getApplicationContext(), popView
                                , (int) (StaticMembers.SCREEN_WIDTH * 0.8), (int) (StaticMembers.SCREEN_HEIGHT * 0.8)
                                , R.style.BottomDialog);
                        titlePop.showAtLocation(llMain, Gravity.CENTER, 0, 0);
                        TextView tvMessage = popView.findViewById(R.id.tvMessage);
                        ImageView ivClose = popView.findViewById(R.id.ivClose);
                        ivClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                titlePop.dismiss();
                            }
                        });
                        tvMessage.setText(Html.fromHtml(lotEndEntity.getShowAlarm()));
                    }
                    tvLogId.setText(lotEndEntity.getLotId());
                    tvEqpId.setText(lotEndEntity.getEqpId());
                    //tvStartTime.setText(lotEndEntity.getTrackInTime());
                    tvStartTime.setText(lotEndEntity.getProcessStartTime());
                    tvEndTime.setText(lotEndEntity.getProcessEndTime());
                    etTouNum.setText(lotEndEntity.getTotalQty());
                    // tvPlanNum.setText(String.valueOf(Integer.parseInt(lotEndEntity.getDoneQty().length() == 0 ? "0" : lotEndEntity.getDoneQty()) / 1000));
                    tvPlanNum.setText(String.valueOf(Integer.parseInt(lotEndEntity.getDoneQty().length() == 0 ? "0" : lotEndEntity.getDoneQty())));//add by bunny
                    etTrueNum.setText(lotEndEntity.getTotalQty());
                    List<AlarmEntity> alarmEntityList = new ArrayList<>();
                    if (lotEndEntity.getMainAlarms().length() > 0) {
                        String[] strs = lotEndEntity.getMainAlarms().split(";");
                        for (String s : strs) {
                            String[] strings = s.split(":");
                            AlarmEntity alarmEntity = new AlarmEntity(strings[0], strings[1]);
                            alarmEntityList.add(alarmEntity);
                        }
                    }
                    alarmListAdapter = new AlarmListAdapter(alarmEntityList);
                    alarmListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    alarmListAdapter.isFirstOnly(true);
                    rvAlarmList.setAdapter(alarmListAdapter);

                    inputList = lotEndEntity.getINPUTDATALIST().getINPUTDATA();

                    rvInputList.setAdapter(inputDataListAdapter);
                    tvUph.setText(lotEndEntity.getUPH());
//                    tvPassRate.setText(lotEndEntity.getYieID());
                } else {
                 /*   loadFail(response.body().getMessage());
                    mHandler.postDelayed(runnable, 1000);*/
                    showdailog(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<LotEndEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEndProcess");
                mHandler.postDelayed(runnable, 1000);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/ShowEndProcess", map, callBack);
    }

    private void refreshPop() {
        generalPop = null;
        tvChoose.setText("请选择");
        rvInputList.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.tvChoose, R.id.tvSubmitInput, R.id.tvSubmitRemark, R.id.rlInput})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.tvChoose:
                if (generalPop == null) {
                    View mView = LayoutInflater.from(this).inflate(R.layout.popupwindow_down_list_select, null);
                    RecyclerView recyclerView = mView.findViewById(R.id.lvDownList);
                    recyclerView.setLayoutManager(new LinearLayoutManager(this));
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                    recyclerView.addItemDecoration(new DividerItemDecoration(this, 1));
                    List<String> list = new ArrayList<>();

                    for (InputDatasEntity.InputObjects inputObjects : inputList) {
                        list.add(inputObjects.getDATACNNAME());
                    }
                    generalPop = new GeneralPop(this, mView
                            , tvChoose.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
                    final PopDownAreaListAdapter popListAdapter = new PopDownAreaListAdapter(list);
                    popListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    popListAdapter.isFirstOnly(true);
                    popListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            if (rvInputList.getVisibility() == View.GONE) {
                                if (animation == null) {
                                    animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                            0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                                    animation.setDuration(500);
                                    animation.setFillAfter(true);
                                }
                                ivDownArrow2.startAnimation(animation);
                                rvInputList.setVisibility(View.VISIBLE);
                            }
                            currentInputObject = inputList.get(position);
                            refreshInputAdapter();
                            popListAdapter.setCurrentSelect(position);
                            popListAdapter.notifyDataSetChanged();
                            tvChoose.setText(String.valueOf(adapter.getItem(position)));
                            generalPop.dismiss();
                        }
                    });
                    recyclerView.setAdapter(popListAdapter);
                    generalPop.setOutsideTouchable(true);
                }
                generalPop.showAsDropDown(tvChoose, 0, 0);
                break;
            case R.id.tvSubmitInput:
                if (tvChoose.getText().toString().equals("请选择")) {
                    ToastUtils.showFreeToast("请选择提交项", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                boolean isInputOk = true;
                if (inputDataListAdapter != null) {
                    submitInputList = inputDataListAdapter.getData();
                    for (InputDataEntity.InputObject inputObject : submitInputList) {
                        inputObject.setEQPID(getEqpID());
                        if (inputObject.getISNULL().equalsIgnoreCase("Y") &&
                                inputObject.getDATAVALUE().length() == 0) {
                            ToastUtils.showFreeToast("请填写带*栏数据", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            isInputOk = false;
                        } else {
                            //add by bunny
                            String datavalue = inputObject.getDATAVALUE();
                            String tounum = etTouNum.getText().toString();
                            if (inputObject.getDATANAME().equals("当前批次的OPEN数据") && datavalue.length() != 0 && tounum.length() != 0) {
                                if (NumberUtils.isNumber(datavalue) && NumberUtils.isNumber(tounum)) {
                                    float f_tounum = Float.parseFloat(tounum);
                                    float f_datavalue = Float.parseFloat(datavalue);
                                    DecimalFormat df = new DecimalFormat("0.00");
                                    String data = df.format((float) f_datavalue / f_tounum * 100);
                                    tvOpen.setText(data);
                                }
                            }
                            if (inputObject.getDATAVALUE().toUpperCase().contains("NG")) {
                                String[] strs = inputObject.getDATAVALUE().split(";");
                                if (strs.length <= 1) {
                                    isInputOk = false;
                                    ToastUtils.showFreeToast("请给NG项填写原因", EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                }
                            }
                        }
                        if (!isInputOk) {
                            break;
                        }
                    }
                }
                if (isInputOk) {
                    requestInputData();
                }
                break;
            case R.id.tvSubmitRemark:
                if (etRemark.getText().toString().trim().length() > 0) {
                    if (lotEndEntity != null) {
                        StartFunctionActivity.requestSubmitRemark(getEqpID(),
                                lotEndEntity.getLotId(), etRemark.getText().toString(), EndFunctionActivity.this, getSupportFragmentManager());
                    } else {
                        ToastUtils.showFreeToast("lot信息还未请求成功",
                                EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    }
                } else {
                    ToastUtils.showFreeToast("请填写备注后再提交",
                            EndFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
                break;
            case R.id.rlInput:
                if (rvInputList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animationDismiss);
                    rvInputList.setVisibility(View.GONE);
                } else {
                    if (animation == null) {
                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setDuration(500);
                        animation.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animation);
                    rvInputList.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void refreshInputAdapter() {
        inputDataListAdapter = new InputDataListAdapter(currentInputObject.getINPUTDATAS().getINPUTDATA());
        inputDataListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        inputDataListAdapter.isFirstOnly(true);
        rvInputList.setAdapter(inputDataListAdapter);
    }

    private void requestInputData() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(EndFunctionActivity.this)) {
                    refreshPop();
                    // requestData(); modify by bunny
                    loadSuccess(response.body().getMessage());
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "SubmitInputData");
            }
        };

        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("DATACNNAME", currentInputObject.getDATACNNAME());
            jsonObject2.put("DATANAME", currentInputObject.getDATANAME());
            if (submitInputList.size() == 0) {
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(submitInputList));
                jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", jsonArray));
            }
            jsonObject.put("INPUTDATA", jsonObject2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("EqpId", getEqpID());
        map.put("InputDataList", jsonObject.toString());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("InputDataType", "LOT");
        NetUtils.requestNet(this, "/SubmitInputData", map, callBack);
    }
//    private void test(){
//        List<String> eqpTypeList = new ArrayList<>();
//        List<String> data = new ArrayList<>();
//
//
//        JSONArray jsonArray = new JSONArray();
//        for (int i = 0; i < eqpTypeList.size(); i++) {
//            JSONObject jsonObject = new JSONObject();
//            JSONArray  jsonArray2 = new JSONArray();
//            String currentType =eqpTypeList[i].EQP_TYPE;
//            for (int j = 0; j < data.size(); j++) {
//
//                JSONObject jsonObject1 = new JSONObject();
//                String eqpType2 = data[j].EQP_TYPE;
//                if (currentType.equals(eqpType2)) {
//                    jsonObject1.put('eqpId', data[j].EQUIPMENT_ID)
//                    jsonObject1.put('color', data[j].COLOR)
//                }
//                jsonArray2.put(jsonObject1);
//            }
//            try {
//                jsonObject.put("'eqpType'", currentType);
//                jsonObject.put("'eqpinfo'", jsonArray2);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            jsonArray.put(jsonObject);
//        }
//    }
}
